import { Message, Radio } from '@arco-design/web-react'
import React from 'react'
import { IApiItem } from '../../../../utils/interfaces'
import { apiStore } from '../../../../utils/store/apiStore'
import Variables from './Variables'

interface IApiExpandedProps {
    apiItem: IApiItem
}

const ApiExpanded: React.FC<IApiExpandedProps> = ({
    apiItem: propsApiItem,
}) => {
    // 数据
    const [values, setValues] = useState(propsApiItem)
    // 使用ref保存数据，避免 使用闭包拿到旧快照 问题
    const valuesRef = useRef(propsApiItem)

    // 点击保存
    const handleSave = async (newValues: IApiItem) => {
        console.log('newValues', newValues)
        // 空值检查
        if (
            !['variables', 'handlers', 'expects', 'label', 'url'].some(
                (k) => !!newValues[k as keyof IApiItem],
            )
        ) {
            Message.warning('内容为空')
            return
        }
        // url必填
        if (!newValues.url) {
            Message.warning('请填写请求地址')
            return
        }
        // 保存数据
        await apiStore.save(newValues)
    }

    // 表单数据变化
    const handleChange = <K extends keyof IApiItem>(
        key: K,
        value: IApiItem[K],
    ) => {
        setValues((prev) => {
            const cloned = { ...prev }
            cloned[key] = value
            valuesRef.current = cloned
            handleSave(cloned)
            return cloned
        })
    }

    // 是默认期望吗
    const isDefaultExpect = () => {
        const values = valuesRef.current
        return !values.expectId || values.expectId === 'default'
    }

    // 变量配置变化
    const handleVariablesChange = (variables: IApiItem['variables']) => {
        const values = valuesRef.current
        // 如果当前选中的是默认期望，则修改变量配置
        if (isDefaultExpect()) {
            handleChange('variables', variables)
            return
        }
        // 修改期望
        const newExpects = values.expects?.map((item) =>
            item.id === values.expectId ? { ...item, variables } : item,
        )
        handleChange('expects', newExpects)
    }
    // 获取当前选中期望的变量配置
    const currentExpectData = () => {
        const values = valuesRef.current
        if (isDefaultExpect()) {
            return { variables: values.variables, handlers: values.handlers }
        }
        const expect = values.expects?.find(
            (item) => item.id === values.expectId,
        )
        return {
            variables: expect?.variables,
            handlers: expect?.handlers,
        }
    }

    return (
        <div>
            {/* 预设 */}
            {(values.expects?.length || 0) > 0 && (
                <div className='flex items-center'>
                    <Radio.Group
                        className='shrink-0'
                        type='button'
                        name='lang'
                        size='mini'
                        defaultValue='default'
                        value={values.expectId || 'default'}
                        onChange={(v) => handleChange('expectId', v)}
                    >
                        <Radio value='default'>默认</Radio>
                        {values.expects?.map((item) => (
                            <Radio key={item.id} value={item.id}>
                                {item.label}
                            </Radio>
                        ))}
                    </Radio.Group>
                </div>
            )}
            {/* 变量 */}
            {!!currentExpectData().variables?.length && (
                <div className='mt-2'>
                    <Variables
                        updateKey={values.expectId || 'default'}
                        isDefault={isDefaultExpect()}
                        defaultExpectVariables={values.variables}
                        value={currentExpectData().variables}
                        onChange={handleVariablesChange}
                    />
                </div>
            )}
        </div>
    )
}

export default ApiExpanded
